#!/usr/bin/env bash
# set -x
set -eo pipefail

SHELL_FOLDER=$(cd $(dirname ${BASH_SOURCE[0]}) && pwd)
DEPLOY_ROOT=$(pwd)

source $DEPLOY_ROOT/init/base.sh

cd $SHELL_FOLDER
INFO "Work/Shell dir: $SHELL_FOLDER"
INFO "Download url: $DOWNLOAD_URL"

BASE_INVENTORY=$(cat ~/.ansible.cfg | grep inventory | awk -F'=' '{print $2}' | awk '$1=$1') 
WARN "Change Download url in $BASE_INVENTORY"
sed -i "s%    download_url:.*%    download_url: $DOWNLOAD_URL%" $BASE_INVENTORY
cat $BASE_INVENTORY | grep download_url

INFO "Create packages download directory."
ansible all[0] -c local -m file -a "path={{download_dir}} state=directory recurse=yes"


INFO "Start to download packages."
ARCH=$(uname -m)
NOTICE "CPU Archicture: $ARCH"

cd $DEPLOY_ROOT/modules
# 过滤空行和以'#'开头的注释行
components=$(cat $DEPLOY_ROOT/modules.list | grep -v '^\s*$' | grep -v '^#')
for module in $components
do
  if [ -f $module/mark_done_download ]; then
    INFO "Packages for $module have already been downloaded."
  elif [ -f $module/download.yaml ]; then
    INFO "Start to download package for $module"
    ansible-playbook $module/download.yaml
    touch $module/mark_done_download
  else
    INFO "Skip download package for $module"
  fi
done

INFO "Show download offline packages number and size: "
ansible all[0] -c local -m shell -a "ls {{download_dir}} | wc -l && du -sh {{download_dir}}"
NOTICE "Download is done."